package filter;


import entity.User816;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "login" , urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LoginFilter.init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("LoginFilter.doFilter");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //强制转化，将父类转化为子类

        String servletPath = httpServletRequest.getServletPath();//获得servlet上下文路径
        System.out.println("servletPath" + servletPath);
        String method = httpServletRequest.getParameter("method");
        //这些就不需要登录凭证
        if (servletPath.equals("/login.jsp")
                || (servletPath.equals("/user816") && (method.equals("login")))
                || servletPath.equals("/fail.html")){
            chain.doFilter(request, response);
            return;
        }

        HttpSession session = httpServletRequest.getSession();
        User816 user816 = (User816) session.getAttribute("user816");
        if (user816 == null){
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
            return;
        }
        chain.doFilter(request, response);
    }


    @Override
    public void destroy() {
        System.out.println("LoginFilter.destroy");
    }
}
